package com.heima.service.impl;

import com.github.pagehelper.PageHelper;
import com.heima.mapper.MerchandiseMapper;
import com.heima.pojo.Merchandise;
import com.heima.pojo.dto.MerchandAddDto;
import com.heima.pojo.dto.MerchandiseDto;
import com.heima.pojo.skuClass;
import com.heima.pojo.vo.MerchandisePagingVO;
import com.heima.service.MerchandiseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class MerchandiseServicelmpl implements MerchandiseService {
    @Autowired
    private MerchandiseMapper merchandiseMapper;
    /**商品分页查询
     * @param dto
     * @return
     */
    @Override
    public MerchandisePagingVO search(MerchandiseDto dto) {

        PageHelper.startPage(dto.getPageIndex(),dto.getPageSize());
        //查询商品表
        List<Merchandise> list = merchandiseMapper.selectBySku(dto.getSkuId());
        //拿到商品分类id
        for (Merchandise lists : list) {
             Long classId = Long.valueOf(lists.getClassId());
             skuClass skuClass = merchandiseMapper.selectById(classId);


             lists.setSkuClass(skuClass);

        }
        MerchandisePagingVO merchandisePagingVo = new MerchandisePagingVO();

        merchandisePagingVo.setCurrentPageRecords(list);
        merchandisePagingVo.setPageIndex(dto.getPageIndex());
        merchandisePagingVo.setPageSize(dto.getPageSize());
        Integer totalCount= merchandiseMapper.getTotal();
        merchandisePagingVo.setTotalCount(totalCount);

        String TotalCount = String.valueOf((int) Math.ceil((double) totalCount / dto.getPageSize()));
        merchandisePagingVo.setTotalPage(Integer.valueOf(TotalCount));
        return merchandisePagingVo;

    }

    /**新增商品
     * @param addDto
     * @return
     */

    @Override
    public Boolean AddMerchand(MerchandAddDto addDto) {
        Merchandise merchandise = new Merchandise();
        merchandise.setCreateTime(LocalDateTime.now());
        merchandise.setUpdateTime(LocalDateTime.now());

        return merchandiseMapper.insert(merchandise);
    }

    /**修改商品
     * @param skuId
     * @return
     */
    @Override
    public Boolean updateMerchand(Long skuId ,MerchandAddDto updateDto) {
        //复制文件
        Merchandise merchandise = new Merchandise();

        BeanUtils.copyProperties(updateDto, merchandise);

        return  merchandiseMapper.updateMerchand(merchandise,skuId);
    }
}
